import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../common/api/index.dart';
import '../../common/style/index.dart';
import '../../common/utils/index.dart';
import '../../common/widgets/index.dart';
import '../../environment_config.dart';
import 'index.dart';

class LoginPage extends GetView<LoginController> {
  const LoginPage({Key? key}) : super(key: key);

  // 头部 logo和名称
  Widget _buildLogo(BuildContext context) {
    return Container(
      width: 110.w,
      margin: EdgeInsets.only(top: (40 + 44.0).h), // 顶部系统栏 44px
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            height: 84.w,
            width: 84.w,
            margin: EdgeInsets.symmetric(horizontal: 15.w),
            child: Stack(
              alignment: Alignment.center,
              children: [
                Positioned(
                  left: 0,
                  top: 0,
                  right: 0,
                  child: Container(
                    height: 84.w,
                    decoration: BoxDecoration(
                      color: Theme.of(context).scaffoldBackgroundColor,
                      boxShadow: const [Shadows.primaryShadow],
                      borderRadius: BorderRadius.all(
                          Radius.circular((84 * 0.5).w)), // 父容器的50%
                    ),
                    child: Container(),
                  ),
                ),
                Positioned(
                  top: 4.w,
                  child: ClipOval(
                      child: ProgramCenterService.to.loginAvatarImageView()),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 15.h),
            child: Text(
              'appName'.tr,
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Theme.of(context).colorScheme.secondary,
                fontFamily: "Montserrat",
                fontWeight: FontWeight.w600,
                fontSize: 24.sp,
                height: 1,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 底部copyright
  Widget _buildBottom() {
    return Obx(() => Container(
          margin: EdgeInsets.only(bottom: 10.h),
          child: Align(
            alignment: Alignment.center,
            child: Text(
                'copy_right'.trArgs(['appName'.tr, controller.state.year])),
          ),
        ));
  }

  // 表单
  Widget _buildInputForm(BuildContext context) {
    return Obx(() => Container(
          width: 295.w,
          margin: EdgeInsets.only(top: 49.h),
          child: Column(children: [
            // 账号输入框
            TextField(
              maxLines: 1,
              autofocus: true,
              style: Theme.of(context).textTheme.bodyMedium,
              keyboardType: TextInputType.text,
              textInputAction: TextInputAction.next,
              controller: controller.userNameController,
              onEditingComplete: () {
                if (controller.state.isPasswordLogin) {
                  FocusScope.of(context).requestFocus(controller.passwordNode);
                } else {
                  FocusScope.of(context).requestFocus(controller.codeNode);
                }
              },
              decoration: InputDecoration(
                labelText: 'login_form_user_name'.tr,
                prefixIcon: Icon(Icons.person,
                    color: Theme.of(context).colorScheme.secondary),
              ),
            ),
            const SizedBox(
              height: 16,
            ),
            // 密码或短信验证码 输入框
            controller.state.isPasswordLogin
                ? _passwordModeTextFormField(context)
                : _codeModeTextFormField(context),
            const SizedBox(
              height: 16,
            ),
            // 登录按钮
            SizedBox(
              width: double.infinity,
              height: 42.h,
              child: O2ElevatedButton(
                () {
                  controller.login();
                },
                Text('login'.tr),
              ),
            ),
            const SizedBox(
              height: 16,
            ),
            Row(
              children: [
                //切换登录模式
                Expanded(
                  child: Visibility(
                      visible: controller.state.isShowChangeLoginModeButton,
                      child: TextButton(
                          onPressed: () => controller.changeLoginMode(),
                          child: Text(
                              controller.state.isPasswordLogin
                                  ? 'login_form_change_login_mode_code'.tr
                                  : 'login_form_change_login_mode_password'.tr,
                              style: Theme.of(context).textTheme.bodySmall))),
                ),
                Expanded(
                    child: Visibility(
                        visible: !EnvironmentConfig.isDirectConnectMode(),
                        child: TextButton(
                            onPressed: () => controller.rebind(),
                            child: Text('login_form_rebind'.tr,
                                style: Theme.of(context).textTheme.bodySmall))))
              ],
            )
          ]),
        ));
  }

  ///
  /// 密码登录
  ///
  Widget _passwordModeTextFormField(BuildContext context) {
    return Obx(() {
      if (controller.state.isCaptcha) {
        return Column(
          children: [
            TextField(
              maxLines: 1,
              obscureText: true,
              style: Theme.of(context).textTheme.bodyMedium,
              focusNode: controller.passwordNode,
              controller: controller.passwordController,
              textInputAction: TextInputAction.next,
              onEditingComplete: () {
                FocusScope.of(context).requestFocus(controller.captchaNode);
              },
              decoration: InputDecoration(
                labelText: 'login_form_user_password'.tr,
                prefixIcon: Icon(Icons.lock,
                    color: Theme.of(context).colorScheme.secondary),
              ),
            ),
            const SizedBox(
              height: 16,
            ),
            Row(
              children: [
                Expanded(
                    flex: 1,
                    child: TextField(
                      maxLines: 1,
                      style: Theme.of(context).textTheme.bodyMedium,
                      keyboardType: TextInputType.number,
                      focusNode: controller.captchaNode,
                      controller: controller.captchaController,
                      textInputAction: TextInputAction.done,
                      decoration: InputDecoration(
                        labelText: 'login_form_user_code'.tr,
                        prefixIcon: Icon(Icons.lock,
                            color: Theme.of(context).colorScheme.secondary),
                      ),
                    )),
                controller.state.captchaBase64String.isEmpty
                    ? TextButton(
                        onPressed: () {
                          controller.getCaptchaImageData();
                        },
                        child: const Text('点击刷新'))
                    : InkWell(
                        onTap: () {
                          controller.getCaptchaImageData();
                        },
                        child: Image.memory(
                          controller.parseCaptchaImg(),
                          width: 100,
                          height: 50,
                          fit: BoxFit.cover,
                        ),
                      )
              ],
            )
          ],
        );
      } else {
        return TextField(
          maxLines: 1,
          obscureText: true,
          style: Theme.of(context).textTheme.bodyMedium,
          focusNode: controller.passwordNode,
          controller: controller.passwordController,
          textInputAction: TextInputAction.next,
          decoration: InputDecoration(
            labelText: 'login_form_user_password'.tr,
            prefixIcon: Icon(Icons.lock,
                color: Theme.of(context).colorScheme.secondary),
          ),
        );
      }
    });
  }

  ///
  /// 短信验证码登录
  ///
  Widget _codeModeTextFormField(BuildContext context) {
    return Row(
      children: [
        Expanded(
          flex: 2,
          child: TextField(
            maxLines: 1,
            obscureText: true,
            style: Theme.of(context).textTheme.bodyMedium,
            keyboardType: TextInputType.text,
            controller: controller.codeController,
            focusNode: controller.codeNode,
            textInputAction: TextInputAction.done,
            decoration: InputDecoration(
              labelText: 'login_form_user_code'.tr,
              prefixIcon: Icon(Icons.lock,
                  color: Theme.of(context).colorScheme.secondary),
            ),
          ),
        ),
        Expanded(
            flex: 1,
            child: CountDownButton(() {
              return controller.onCheckMobile();
            }, () {
              OLogger.d('发送短信。。。。');
              controller.sendSmsCode();
            }))
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LoginController>(
      builder: (_) {
        return Scaffold(
          // resizeToAvoidBottomInset: false,
          body: PageScrollContentWidget(
            contentWidget: Column(
              children: <Widget>[
                _buildLogo(context),
                _buildInputForm(context),
                const Spacer(),
                _buildBottom(),
              ],
            ),
          ),
        );
      },
    );
  }
}
